<template>
  <el-dialog
    :model-value="rolesVisible"
    title="分配角色"
    width="40%"
    @close="handleClose"
  >
    <el-tree
     :data="roles"
     show-checkbox
     node-key="id"
     :props="defineProps"
     :default-checked-keys="form.roleIds"
     @check="handleCurrentChecked"
    ></el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { saveRole } from '../../../api/user'
import { ElMessage } from 'element-plus'

const roles = ref([])
const form = ref({
  adminId: 0,
  roleIds: []
})

const props = defineProps({
  // 编辑行数据
  rolesValue: {
    type: Object,
    default: () => {}
  },
  rolesIdsValue: {
    type: Object,
    default: () => {}
  },
  adminIdValue: {
    type: Object,
    default: () => {}
  }
})
// 监听props.dialogRowValue值改变
watch(
  () => props.dialogRowValue,
  () => {
    // console.log(props.dialogRowValue)
    roles.value = props.rolesValue
    form.value.roleIds = props.rolesIdsValue
    form.value.adminId = props.adminIdValue
  },
  { deep: true, immediate: true }
)

const emits = defineEmits(['update:modelValue'])

function handleCurrentChecked(nodeObj, selectedObj) {
  form.value.roleIds = selectedObj.checkedKeys
}

// 关闭
function handleClose() {
  emits('update:modelValue', false)
}
// 确认
async function handleConfirm() {
  const resp = await saveRole(form.value)
  if (resp.data.code === '200') {
    ElMessage({
      message: '更新成功',
      type: 'success'
    })
  }
  handleClose()
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__prefix-inner {
  align-items: center;
}
</style>
